﻿using EasyXaf.EntityDesigner.BusinessObjects.Entities.EntityProperties;
using EasyXaf.EntityDesigner.BusinessObjects.Entities.ValidationRules;

namespace EasyXaf.EntityDesigner.Commands.PropertyTypeBuilders;

public class EntityTypeBuilder
{
    public static bool Build(EntityProperty property, string typeName)
    {
        bool isRequired = false;
        bool isCollection = false;

        if (typeName.EndsWith('!'))
        {
            isRequired = true;
            typeName = typeName[..^1];
        }
        else if (typeName.EndsWith('?'))
        {
            typeName = typeName[..^1];
        }
        else if (typeName.EndsWith("[]"))
        {
            isCollection = true;
            typeName = typeName[..^2];
        }

        var entity = property.Entity.DomainModel.AllEntities.FirstOrDefault(e => e.Name == typeName);
        if (entity != null)
        {
            property.EntityType = entity;

            if (isCollection)
            {
                property.PropertyType = PropertyType.EntityCollection;
            }
            else
            {
                property.PropertyType = PropertyType.Entity;

                if (isRequired)
                {
                    property.Entity.ValidationRules.Add(new RequiredRule(property.Session)
                    {
                        TargetProperty = property,
                    });
                }
            }

            return true;
        }

        return false;
    }
}
